using System;
using System.ComponentModel;
using System.Linq;

namespace TrueCode.Core.EditableEntity
{
    [Serializable]
  public class EditableObject : INotifyPropertyChanged
  {
    #region Fields
        [NonSerialized]
    private static int _keyGenerator;
        [NonSerialized]
    private readonly int _key;
        [NonSerialized]
    //private readonly EventHandler _setDirty;
    private IEditableValue[] _properties;
    #endregion
    
    #region .ctor
    public EditableObject()
    {
      _key = _keyGenerator++;
//      _setDirty = (s, e) => RaisePropertyChanged( "IsDirty" );
    }
    #endregion

    #region IEditable Implementation
    public int Key
    {
      get { return _key; }
    }

    public virtual bool IsDirty
    {
      get { return _properties.Any( p => p.IsDirty ); }
    }

    public virtual void AcceptChanges()
    {
      _properties.ForEach( p => p.AcceptChanges() );
    }

    public virtual void RejectChanges()
    {
      _properties.ForEach( p => p.RejectChanges() );
    }
    #endregion

    #region Protected
    protected void InitializeEditableObject( params IEditableValue[] properties )
    {
      _properties = properties;
//      foreach( var property in _properties )
//        property.IsDirtyChanged += _setDirty;
    }
    #endregion

    #region Implementation of INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged( string propertyName )
    {
      PropertyChanged.Raise( this, propertyName );
    }
    #endregion
  }
}